<template>
	<div>
		<cus-modal
			ref="modal"
			title="编辑"
			@on-visible-change="onVisibleChange"
			@onOk="onOk"
		>
			<Form
				ref="formValidate"
				:model="form"
				:rules="ruleValidate"
				:label-width="100"
			>
				<FormItem
					label="角色名称"
					prop="name"
					:rules="{
						required: true,
						message: '角色名称不能为空',
						trigger: 'blur'
					}"
				>
					<Input
						v-model="form.name"
						style="width: 200px"
						placeholder="请输入名称"
					></Input>
				</FormItem>
				<FormItem label="描述" prop="descr">
					<Input
						v-model="form.descr"
						type="textarea"
						:maxlength=50
						show-word-limit
						:autosize="{ minRows: 3, maxRows: 5 }"
						style="width: 500px"
						placeholder="请输入描述"
					/>
				</FormItem>
				<FormItem label="权限列表" prop="resourceIdList">
					<div class="permission hide-scrollbar">
						<roleTree
							ref="roleTree"
							v-if="!form.id || form.resourceIdList.length"
							@onOver="onOver"
							@onReady="
								() => {
									this.loading = false
								}
							"
							:resourceIdList.sync="form.resourceIdList"
						></roleTree>
					</div>
				</FormItem>
				<div class="flex">
					<Icon
						type="ios-alert"
						size="20"
						style="margin-right: 5px;"
						color="orange"
					/>
					菜单修改需刷新页面或重新登录后生效
				</div>
			</Form>
			<Spin size="large" fix v-if="loading"></Spin>
		</cus-modal>
	</div>
</template>

<script>
import {
	getRoleInfo,
	addRole,
	modifyRole,
	getRolePermission,
	modifyRolePermission
} from '@/api/business/system'
import roleTree from './roleTree'

const form = {
	id: '',
	name: '',
	descr: '',
	resourceId: [],
	resourceIdList: []
}

export default {
	components: { roleTree },
	name: 'roleModal',
	data() {
		return {
			loading: false,
			form: form,
			ruleValidate: {
				resourceIdList: [
					{
						required: true,
						validator: (rule, value, callback) => {
							if (!this.form.resourceId.length) {
								return callback(new Error('权限列表不能为空'))
							} else return callback()
						},
						trigger: 'blur'
					}
				]
			}
		}
	},
	mounted() {
		this.form = this.$cu.deepClone(form)
	},
	methods: {
		onVisibleChange(v) {
			this.$refs['formValidate'].resetFields()
			if (!v) this.form = this.$cu.deepClone(form)
		},
		show() {
			this.loading = false
			this.$refs['modal'].show = true
			if (this.form.id) {
        this.loading = true
				Promise.all([this.getRoleInfoApi()]).then(() => {
					this.getRolePermissionApi()
				})
			}else{
        this.loading = true
        this.form.resourceIdList = []
        this.$refs.roleTree.getJsonMenuListApi()
      }
		},
		onOver(ids) {
			this.form.resourceId = ids
		},
		onOk() {
			this.$refs['roleTree'].getCheckedAndIndeterminateNodes()
			this.$refs['formValidate'].validate((valid) => {
				if (valid) {
					this.$nextTick(() => {
						this.loading = true
						if (this.form.id) {
							this.modifyRoleApi()
						} else this.addRoleApi()
					})
				}
			})
		},
		// 获取角色详情
		getRoleInfoApi() {
			return new Promise((resolve) => {
				getRoleInfo({ id: this.form.id }).then((res) => {
					if (res.code === 1) {
						res.data.resourceIdList = []
						this.form = res.data
						resolve()
					}
				})
			})
		},
		getRolePermissionApi() {
			return new Promise((resolve) => {
        if(this.form.id){
          getRolePermission({ roleId: this.form.id }).then((res) => {
            if (res.code === 1) {
              this.form.resourceIdList = res.data
              resolve()
            }
          })
        }else{
          this.form.resourceIdList = []
        }

			})
		},
		// 添加角色接口
		addRoleApi() {
			return new Promise((resolve) => {
				addRole({
					name: this.form.name,
					descr: this.form.descr
				}).then((res) => {
					if (res.code === 1) {
						this.form.id = res.data
						this.modifyRolePermissionApi().then(() => {
							this.loading = false
							this.$Message.success('添加成功')
							this.$refs['modal'].show = false
							this.$parent.onInit()
						})
						resolve()
					} else this.loading = false
				})
			})
		},
		// 编辑角色接口
		modifyRoleApi() {
			return new Promise((resolve) => {
				modifyRole({
					id: this.form.id,
					name: this.form.name,
					descr: this.form.descr
				}).then((res) => {
					if (res.code === 1) {
						this.modifyRolePermissionApi().then(() => {
							this.loading = false
							this.$Message.success('编辑成功')
							this.$refs['modal'].show = false

							// 判断是否为当前用户
							if (this.vuex_user.role.filter((v) => v.id == this.form.id)) {
								this.$cu
									.dialog({
										title: '提示',
										content:
											'修改的为当前用户角色,需要刷新页面才可生效,是否立即刷新'
									})
									.then(() => {
										window.location.reload()
									})
							}

							this.$parent.onInit()
						})
						resolve()
					} else this.loading = false
				})
			})
		},
		// 编辑权限
		modifyRolePermissionApi() {
			return new Promise((resolve) => {
				modifyRolePermission({
					roleId: this.form.id,
					resourceIdList: JSON.stringify(this.form.resourceId)
				}).then((res) => {
					if (res.code === 1) {
						resolve()
					} else this.loading = false
				})
			})
		}
	}
}
</script>

<style scoped lang="less">
.permission {
	/*height: 300px;*/
	max-height: 420px;
	width: 500px;
	border: 1px solid #dcdee2;
	overflow-y: auto;
	overflow-x: hidden;
	border-radius: 2px;
	padding: 0 0 0 10px;
}

.permission::-webkit-scrollbar {
	display: none;
}
</style>
